var token = window.sessionStorage.getItem("token");
// session 未获取到会话 跳转到登录页面
// 验证用户是否登录
var username = window.sessionStorage.getItem("user");
if (username !== undefined && !username == "iocc") {
$.ajax({
    type: "get",
    url: "http://11.16.125.16:10004/verifyUserToken",
    cache: false,
    async: false,
    data: {},
    headers: {
        "authorization": token
    },
    dataType: 'json', //请求的数据类型
    success: function (data) { //请求的返回成功的方法
        if (!data.result) {
            window.location.href = "http://11.16.127.79/portal/index.html";
        }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) { //请求的失败的返回的方法
        console.log("账号禁用或账号被使用,请重新登录!");
    }
});
}
//开始日期选择后，结束日期的最小值为开始日期
function laydatechange(date) {
    var newObj = {};
    date.month = date.month - 1;
    $.each(date, function (i, item) {
        newObj[i] = item;
    });
    return newObj;
}
var logOutIP = 'http://11.16.125.16:10004';
var token= window.localStorage.getItem("token");
if(token==null){
    token=getUrlParam("token");
}
var serverIP = 'http://11.16.127.79:80';
　　　var oldTime = new Date().getTime();
        var newTime = new Date().getTime();
        var outTime = 10* 60 * 1000; //设置超时时间： 15分钟

        $(function(){
            /* 鼠标移动事件 */
            $(document).mouseover(function(){
                oldTime = new Date().getTime(); //鼠标移入重置停留的时间

            });
            function watermark(settings) {
                //默认设置
                var defaultSettings={
                    watermark_txt:"GZW\n"+Date.parse(new Date()).toString().substring(0,10),
                    watermark_x:0,//水印起始位置x轴坐标
                    watermark_y:80,//水印起始位置Y轴坐标
                    watermark_rows:9,//水印行数
                    watermark_cols:13,//水印列数
                    watermark_x_space:0,//水印x轴间隔
                    watermark_y_space:0,//水印y轴间隔
                    watermark_color:'#ffffff',//水印字体颜色
                    watermark_alpha:0.05,//水印透明度
                    watermark_fontsize:'24px',//水印字体大小
                    watermark_fontWeight:'10',//水印字体加粗
                    watermark_font:'微软雅黑',//水印字体
                    watermark_width:150,//水印宽度
                    watermark_height:90,//水印长度
                    watermark_angle:321//水印倾斜度数
                };
                //采用配置项替换默认值，作用类似jquery.extend
                if(arguments.length===1&&typeof arguments[0] ==="object" )
                {
                    var src=arguments[0]||{};
                    for(key in src)
                    {
                        if(src[key]&&defaultSettings[key]&&src[key]===defaultSettings[key])
                            continue;
                        else if(src[key])
                            defaultSettings[key]=src[key];
                    }
                }
            
                var oTemp = document.createDocumentFragment();
            
            //     //获取页面最大宽度
            //     var page_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
            //     //获取页面最大长度
            //     var page_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
            
            //     //如果将水印列数设置为0，或水印列数设置过大，超过页面最大宽度，则重新计算水印列数和水印x轴间隔
            //     if (defaultSettings.watermark_cols == 0 ||
            //    　　　　(parseInt(defaultSettings.watermark_x 
            // 　　　　+ defaultSettings.watermark_width *defaultSettings.watermark_cols 
            // 　　　　+ defaultSettings.watermark_x_space * (defaultSettings.watermark_cols - 1)) 
            // 　　　　> page_width)) {
            //         defaultSettings.watermark_cols = 
            // 　　　　　　parseInt((page_width
            // 　　　　　　　　　　-defaultSettings.watermark_x
            // 　　　　　　　　　　+defaultSettings.watermark_x_space) 
            // 　　　　　　　　　　/ (defaultSettings.watermark_width 
            // 　　　　　　　　　　+ defaultSettings.watermark_x_space));
            //         defaultSettings.watermark_x_space = 
            // 　　　　　　parseInt((page_width 
            // 　　　　　　　　　　- defaultSettings.watermark_x 
            // 　　　　　　　　　　- defaultSettings.watermark_width 
            // 　　　　　　　　　　* defaultSettings.watermark_cols) 
            // 　　　　　　　　　　/ (defaultSettings.watermark_cols - 1));
            //     }
                //如果将水印行数设置为0，或水印行数设置过大，超过页面最大长度，则重新计算水印行数和水印y轴间隔
            //     if (defaultSettings.watermark_rows == 0 ||
            //    　　　　(parseInt(defaultSettings.watermark_y 
            // 　　　　+ defaultSettings.watermark_height * defaultSettings.watermark_rows 
            // 　　　　+ defaultSettings.watermark_y_space * (defaultSettings.watermark_rows - 1)) 
            // 　　　　> page_height)) {
            //         defaultSettings.watermark_rows = 
            // 　　　　　　parseInt((defaultSettings.watermark_y_space 
            // 　　　　　　　　　　　+ page_height - defaultSettings.watermark_y) 
            // 　　　　　　　　　　　/ (defaultSettings.watermark_height + defaultSettings.watermark_y_space));
            //         defaultSettings.watermark_y_space = 
            // 　　　　　　parseInt((page_height 
            // 　　　　　　　　　　- defaultSettings.watermark_y 
            // 　　　　　　　　　　- defaultSettings.watermark_height 
            // 　　　　　　　　　　* defaultSettings.watermark_rows) 
            // 　　　　　　　　　/ (defaultSettings.watermark_rows - 1));
            //     }
                var x;
                var y;
                for (var i = 0; i < defaultSettings.watermark_rows; i++) {
                    y = defaultSettings.watermark_y + (defaultSettings.watermark_y_space + defaultSettings.watermark_height) * i;
                    for (var j = 0; j < defaultSettings.watermark_cols; j++) {
                        x = defaultSettings.watermark_x + (defaultSettings.watermark_width + defaultSettings.watermark_x_space) * j;
            
                        var mask_div = document.createElement('div');
                        mask_div.id = 'mask_div' + i + j;
                        mask_div.appendChild(document.createTextNode(defaultSettings.watermark_txt));
                        //设置水印div倾斜显示
                        mask_div.style.webkitTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                        mask_div.style.MozTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                        mask_div.style.msTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                        mask_div.style.OTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                        mask_div.style.transform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
                        mask_div.style.visibility = "";
                        mask_div.style.position = "absolute";
                        mask_div.style.left = x + 'px';
                        mask_div.style.top = y + 'px';
                        mask_div.style.overflow = "hidden";
                        mask_div.style.zIndex = "9999";
                        mask_div.style.pointerEvents="none";
                        //mask_div.style.border="solid #eee 1px";
                        mask_div.style.opacity = defaultSettings.watermark_alpha;
                        mask_div.style.fontSize = defaultSettings.watermark_fontsize;
                        mask_div.style.fontWeight = defaultSettings.watermark_fontWeight;
                        mask_div.style.fontFamily = defaultSettings.watermark_font;
                        mask_div.style.color = defaultSettings.watermark_color;
                        mask_div.style.textAlign = "center";
                        mask_div.style.width = defaultSettings.watermark_width + 'px';
                        mask_div.style.height = defaultSettings.watermark_height + 'px';
                        mask_div.style.display = "block";
                        oTemp.appendChild(mask_div);
                    };
                };
                document.body.appendChild(oTemp);
            }
            setTimeout(function(){
                var user=window.sessionStorage.getItem("user");
                if(window.sessionStorage.getItem("user")=="csdn"||window.sessionStorage.getItem("user")==null){
                    user="GZW";
                }
                watermark({ watermark_txt: user+"\n"+Date.parse(new Date()).toString().substring(0,10) })
            },500)   
        });

        function OutTime(){
            newTime = new Date().getTime(); //更新未进行操作的当前时间
            if(newTime - oldTime > outTime){ //判断是否超时不操作
             
                $.ajax({
                    type: "get", //向后台请求的方式，有post，get两种方法
                    url: logOutIP + "/ajaxLogout", //url填写的是请求的路径
                    cache: false, //缓存是否打开
                    // data: {//请求的数据，
                    // },
                    headers: {
                        "authorization": token
                    },
                    dataType: 'json', //请求的数据类型
                    success: function (data) { //请求的返回成功的方法
                        if (data) {
                            console.log("注销成功。");
                            window.localStorage.clear(); //清空所有的存储数据
                            window.sessionStorage.clear();
                            window.location.href = serverIP + "/portal/index.html";
                        } else {
                            console.log("注销失败，原因：" + data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) { //请求的失败的返回的方法
                        console.log("注销失败，请稍后再次尝试！");
                    }
                });
            }
        }

        /* 定时器  判断每5秒是否长时间未进行页面操作 */
      //  window.setInterval(OutTime, 5000);
// 高级检索展开与关闭

function advancedSearch(bind_id, slide_id) {
    $("#" + bind_id).click(function () {
        if ($("#" + slide_id).attr('open')) {
            $("#" + slide_id).stop();
            $("#" + slide_id).slideUp(500);
            $("#" + slide_id).attr("open", false);
            $("#" + bind_id).children('i').css({
                'transform': 'rotate(180deg)'
            });
        } else {
            $("#" + slide_id).stop();
            $("#" + slide_id).slideDown(500);
            $("#" + slide_id).attr("open", true);
            $("#" + bind_id).children('i').css({
                'transform': 'rotate(360deg)'
            });
        }
        setTimeout(function () {
            $(window).resize();
        }, 1000);
    });
}
function distanceAddress(lon, lat) {
    var address = ""
    $.ajax({
        type: 'get',
        dataType: "json",
        url: serUrl_port2 + "/VIAS/web/snapshot/baidu/RectangleRetrievel",
        data: {
            httpurl: "/geocoding?location=" + lat + "," + lon + "&output=json"
        },
        async: false,
        success: function(data) {
            if (data.message == "ok") {
                address = "该坐标距离" + data.results[0].pois[0].address + data.results[0].pois[0].distance + "米";
            }
        }
    })
    return address;
}
//获取url后的参数值
function getUrlParam(key, url) {
    var href = url || window.location.href;
    var url = href.split("?");
    if (url.length <= 1) {
        return "";
    }
    var params = url[1].split("&");

    for (var i = 0; i < params.length; i++) {
        var param = params[i].split("=");
        if (key == param[0]) {
            if (url[2] != undefined) {
                return decodeURIComponent(param[1] + '?' + url[2]);
            }
            return decodeURIComponent(param[1]);
        }
    }
}

function formatDate(now) {
    var year = now.getFullYear();  //取得4位数的年份
    var month = now.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月
    var date = now.getDate();      //返回日期月份中的天数（1到31）
    var hour = now.getHours();     //返回日期中的小时数（0到23）
    var minute = now.getMinutes(); //返回日期中的分钟数（0到59）
    var second = now.getSeconds(); //返回日期中的秒数（0到59）
    return year + "年" + month + "月" + date + "日" + hour + ":" + minute + ":" + second;
}

//时间转string
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份  
        "d+": this.getDate(), //日  
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时  
        "H+": this.getHours(), //小时  
        "m+": this.getMinutes(), //分  
        "s+": this.getSeconds(), //秒  
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
        "S": this.getMilliseconds() //毫秒  
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

//获取前后的时间  返回的时间格式为'2018-04-28 00:00:00'  n为正数 往后n天  n为负数 往前n天
function getCurrentDay(n) {
    var today = new Date(),
        date;
    return n ? (new Date(today.getTime() + n * 1000 * 60 * 60 * 24)).pattern("yyyy-MM-dd HH:mm:ss") : new Date().pattern("yyyy-MM-dd HH:mm:ss")
}

//打开设备选择相关注册方法  和回调
var equipmentObj = {
    zTreeNodes: [],
    finCallback: null,
    chooseEquipment: function (id, finCallback) { //打开设备选择的方法
        $("#" + id).off('click').on('click', function () {
            equipmentObj.finCallback = finCallback;
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 2,
                    title: ['设备选择', 'font-size:22px;font-blod;font-weight: bold;padding-left:40px;color:white;background:#2180d4;'],
                    //content: '../staticfacedatabase/index.html', //看了你车辆频次页面，设备选择显示正常
                    content: '/vias_app/views/vias/snapshot/staticfacedatabase/index.html',
                    area: ['650px', '850px'],
                    shade: 0.8
                });
            });
        });
    },
    ztreeback: function (callback) {
        $.ajax({
            type: 'put',
            url: 'http://11.16.127.79:10001/server-sysmanager/queryEnumerationList',
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                enumerationNum: '1'
            }),
            success: function (tagdata) {
                console.log(tagdata);
                callback(tagdata);
            },
            error: function (err) {
                //如果标签未查询到  默认查询所有
                callback();
                console.log('获取标签接口异常...' + err);
            }
        });
    },
    getAllData: function () {
        var _index;
        layui.use('layer', function () {
            _index = layer.load(1);
        });
        $.ajax({
            type: 'get',
            url: '/vias_app/static/common/js/allDevice.json',
            dataType: 'json',
            async: false,
            success: function (data) {
                console.log(data);
                layer.close(_index);
                if (data.responseCode == '1000') {
                    if (data.content.length > 0) {
                        data.content.forEach(function (item, index) {
                            if (item.id) {
                                item.title = item.name;
                                if (item.keyNum != null) {
                                    item.name = item.name + '----[' + item.keyNum + ']';
                                }
                                if (item.type == "APE") {
                                    item.iconSkin = 'icon_level_4';
                                } else if (item.type == "ORG") {
                                    if (item.level == "1") {
                                        item.iconSkin = 'icon_level_1';
                                    } else if (item.level == "2") {
                                        item.iconSkin = 'icon_level_2';
                                    } else {
                                        item.iconSkin = 'icon_level_3';
                                    }
                                }
                                item.open = false;
                                equipmentObj.zTreeNodes.push(item);
                            }
                        });
                    } else {
                        layer.msg('暂无数据');
                    }
                } else {
                    console.log('接口出问题了！');
                }

            },
            error: function () {
                layer.close(_index);
                console.log('接口出问题了！');
            }
        });
    },

    ztree_data: function (apeLabel, callback) {
        var d1 = new Date()
        var _index;
        layui.use('layer', function () {
            _index = layer.load(1);
        });
        $.ajax({
            type: 'get',
            url: serUrl_port6 + 'VIAS/System/Ape//findStreet',
            dataType: 'json',
            data: {
                apeName: apeLabel
            },
            success: function (data) {
                console.log(data);
                var d2 = new Date()
                console.log(parseInt(d2 - d1) / 1000);
                var zNodes = [];
                layer.close(_index);
                if (data.responseCode == '1000') {
                    if (data.content.length > 0) {
                        data.content.forEach(function (item, index) {
                            if (item.RN) {
                                item.name = item.LXFS;
                                item.id = item.RN;
                                item.title = item.name;
                                if (item.keyNum != null) {
                                    //item.name=item.name+'<span style="color:red;display:none">['+item.keyNum+']</span>';
                                    item.name = item.name + '----[' + item.keyNum + ']';
                                }
                                if (item.type == "APE") {
                                    item.iconSkin = 'icon_level_4';
                                    // if(item.status == '1'){
                                    //     item.iconSkin = 'icon_level_4';
                                    // }else{
                                    //     item.iconSkin = 'icon_level_5';
                                    // }
                                } else if (item.type == "ORG") {
                                    if (item.level == "1") {
                                        item.iconSkin = 'icon_level_1';
                                    } else if (item.level == "2") {
                                        item.iconSkin = 'icon_level_2';
                                    } else {
                                        item.iconSkin = 'icon_level_3';
                                    }
                                }
                                item.open = false;
                                zNodes.push(item);
                            }
                            //icon_level_1 icon_level_2 icon_level_3 icon_level_4 icon_level_5
                            //item.nocheck 隐藏显示
                            //1表示最外层图标 2是第二级 3是第三级 4表示圆形摄像头 5表示直摄像头              
                        });
                        callback(zNodes);
                    } else {
                        layer.msg('暂无数据');
                    }
                } else {
                    console.log('接口出问题了！');
                }

            },
            error: function () {
                layer.close(_index);
                console.log('接口出问题了！');
            }
        });
    },
    _finalchoose: function (finalChooseArr) {
        if (equipmentObj.finCallback && typeof (equipmentObj.finCallback) == "function") {
            equipmentObj.finCallback(finalChooseArr);
        }
    },
    _hidediv: function (index) {
        layer.close(index);
    }
}
var equipmentRadioObj = {
    zTreeNodes: [],
    finCallback: null,
    chooseEquipment: function (id, finCallback) { //打开设备选择的方法
        $("#" + id).off('click').on('click', function () {
            equipmentRadioObj.finCallback = finCallback;
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 2,
                    title: ['设备选择', 'font-size:22px;font-blod;font-weight: bold;padding-left:40px;color:white;background:#2180d4;'],
                    content: '/vias_app/views/vias/snapshot/staticfacedatabaseRadio/index.html',
                    area: ['650px', '850px'],
                    shade: 0.8
                });
            });
        });
    },
    getAllData: function () {
        var _index;
        layui.use('layer', function () {
            _index = layer.load(1);
        });
        $.ajax({
            type: 'get',
            url: '/vias_app/static/common/js/allDevice.json',
            dataType: 'json',
            async: false,
            success: function (data) {
                console.log(data);
                layer.close(_index);
                if (data.responseCode == '1000') {
                    if (data.content.length > 0) {
                        data.content.forEach(function (item, index) {
                            if (item.id) {
                                item.title = item.name;
                                if (item.keyNum != null) {
                                    item.name = item.name + '----[' + item.keyNum + ']';
                                }
                                if (item.type == "APE") {
                                    item.iconSkin = 'icon_level_4';
                                } else if (item.type == "ORG") {
                                    if (item.level == "1") {
                                        item.iconSkin = 'icon_level_1';
                                    } else if (item.level == "2") {
                                        item.iconSkin = 'icon_level_2';
                                    } else {
                                        item.iconSkin = 'icon_level_3';
                                    }
                                }
                                item.open = false;
                                equipmentRadioObj.zTreeNodes.push(item);
                            }
                        });
                    } else {
                        layer.msg('暂无数据');
                    }
                } else {
                    console.log('接口出问题了！');
                }

            },
            error: function () {
                layer.close(_index);
                console.log('接口出问题了！');
            }
        });
    },
    ztreeback: function (callback) {
        $.ajax({
            type: 'put',
            url: 'http://11.16.127.79:10001/server-sysmanager/queryEnumerationList',
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                enumerationNum: '1'
            }),
            success: function (tagdata) {
                console.log(tagdata);
                callback(tagdata);
            },
            error: function (err) {
                //如果标签未查询到  默认查询所有
                callback();
                console.log('获取标签接口异常...' + err);
            }
        });
    },
    ztree_data: function (apeLabel, callback) {

        var d1 = new Date()
        var _index;
        layui.use('layer', function () {
            _index = layer.load(1);
        });
        $.ajax({
            type: 'get',
            url: serUrl_port6 + 'VIAS/System/Ape//findStreet',
            dataType: 'json',
            data: {
                apeName: apeLabel
            },
            success: function (data) {
                var d2 = new Date()
                console.log(parseInt(d2 - d1) / 1000);
                var zNodes = [];
                layer.close(_index);
                if (data.responseCode == '1000') {
                    if (data.content.length > 0) {
                        data.content.forEach(function (item, index) {
                            if (item.RN) {
                                item.name = item.LXFS;
                                item.id = item.RN;
                                item.title = item.name;
                                if (item.keyNum != null) {
                                    //item.name=item.name+'<span style="color:red;display:none">['+item.keyNum+']</span>';
                                    item.name = item.name + '----[' + item.keyNum + ']';
                                }
                                if (item.type == "APE") {
                                    item.iconSkin = 'icon_level_4';
                                    // if(item.status == '1'){
                                    //     item.iconSkin = 'icon_level_4';
                                    // }else{
                                    //     item.iconSkin = 'icon_level_5';
                                    // }
                                } else if (item.type == "ORG") {
                                    if (item.level == "1") {
                                        item.iconSkin = 'icon_level_1';
                                    } else if (item.level == "2") {
                                        item.iconSkin = 'icon_level_2';
                                    } else {
                                        item.iconSkin = 'icon_level_3';
                                    }
                                }
                                item.open = false;
                                zNodes.push(item);
                            }
                            //icon_level_1 icon_level_2 icon_level_3 icon_level_4 icon_level_5
                            //item.nocheck 隐藏显示
                            //1表示最外层图标 2是第二级 3是第三级 4表示圆形摄像头 5表示直摄像头              
                        });
                        callback(zNodes);
                    } else {
                        layer.msg('暂无数据');
                    }
                } else {
                    console.log('接口出问题了！');
                }

            },
            error: function () {
                layer.close(_index);
                console.log('接口出问题了！');
            }
        });
    },
    _finalchoose: function (finalChooseArr) {
        if (equipmentRadioObj.finCallback && typeof (equipmentRadioObj.finCallback) == "function") {
            equipmentRadioObj.finCallback(finalChooseArr);
        }
    },
    _hidediv: function (index) {
        layer.close(index);
    }
}
//打开车辆选择的方法
var carObj = {
    openindex: null,
    openflag: true,
    callback: null,
    chooseCar: function (id, callback) {
        $("#" + id).off('click').on('click', function () {
            carObj.callback = callback;
            if (carObj.openflag) {
                layui.use('layer', function () {
                    var layer = layui.layer;
                    carObj.openindex = layer.open({
                        type: 2,
                        title: ['车辆选择', 'font-size:22px;font-blod;font-weight: bold;padding-left:40px;color:white;background:#2180d4;'],
                        content: '../choosecar/index.html',
                        area: ['910px', '650px'],
                        shade: 0, //遮罩层
                        cancel: function (index, layno) {
                            $("#layui-layer" + index).hide();
                            return false;
                        }
                    });
                });
                carObj.openflag = false;
            } else {
                var id = $('.layui-layer-iframe').attr("id");
                $("#" + id).show();
            }
        });
    },
    //此方法为打开车辆 确认选择之后的回掉 
    //第一个：type 为1的时候表示车辆选择为0，2为选择了车辆  第二个参数为打开的iframe的index，用于拼接该iframe层的id 第3个len为 选择的数量 第4个val为选择车辆的 ss_id的集合
    _getlayuiback: function (type, index, len, val) {
        $("#layui-layer" + index).hide(); //确认选择完成之后并不关闭iframe层 只是隐藏
        if (type == "2") carObj.callback(len, val); //type为2表示选择了车辆 只有选择了车辆的情况下才执行回掉
    }
}


/*查询结果div返回顶部*/
function gotop(id, div_id) {
    var offset = 100; //滚动条距离顶部的位置
    $('#' + div_id).scroll(function () {
        ($(this).scrollTop() > offset) ? $("#" + id).show() : $("#" + id).hide();
    });
    //smooth scroll to top
    $("#" + id).on('click', function (event) {
        event.preventDefault();
        $('#' + div_id).animate({
            scrollTop: 0,
        }, 700);
    });
}

//下拉多选公共方法
function _showchoose_count(static_msg, msg, num) {
    num == 0 ? $("#_chooseresult").text(static_msg) : $("#_chooseresult").text(msg);
}

//地图选点公共方法
var mapObj = {
    _data: null,
    chooseAreaWithMap: function (id, callback) {
        $("#" + id).off('click').on('click', function () {
            mapObj._data = null;
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.open({
                    type: 2,
                    shadeClose: true,
                    shade: 0.8,
                    scrollbar: false,
                    title: ['地图选点', 'font-size:22px;font-blod;font-weight: bold;padding-left:40px;color:white;background:#2180d4;'],
                    content: 'http://11.16.127.79/ditu/car.html?ip=' + location.href,
                    area: ['1200px', '800px'],
                    end: function () {
                        callback(mapObj._data);
                    }
                });
            })

        });
    },
    _databack: function (data) {
        mapObj._data = data;
    }
}

//图片加载失败时显示暂无图片
function imgerror(obj) {
    $(obj).attr('src', '/vias_app/static/vias/images/getphotoerr.jpg');
}


//传入json数据及 key 返回对应的text  json数据格式 [{key:'1',"text":'我是text'}]
function returntext(obj, key) {
    if (key == undefined || key == "") return "";
    var text = '';
    for (var i = 0, len = obj.length; i < len; i++) {
        if (obj[i].key == key) {
            text = obj[i].text;
            break;
        }
    }
    return text;
}

function advancedSearchShow(bind_id, slide_id, callback) {
    var state = 0;
    $("#" + bind_id).click(function () {
        if ($("#" + slide_id).attr("class") == "") {
            $("#" + slide_id).stop();
            $("#" + slide_id).slideUp(900);
            $("#" + slide_id).attr("class", "hide-search");
            state = 1;
            $("#" + bind_id + " i").removeClass("icon-icon-106").addClass("icon-icon-107")
        } else {
            $("#" + slide_id).stop();
            $("#" + slide_id).slideDown(900);
            $("#" + slide_id).attr("class", "");
            $("#" + bind_id + " i").removeClass("icon-icon-107").addClass("icon-icon-106")
            callback();
        }
        setTimeout(function () {
            $(window).resize();
        }, 1000);
    });
}

// 高级检索展开与关闭

function advancedSearchBack(bind_id, slide_id, callback) {
    $("#" + bind_id).click(function () {
        if ($("#" + slide_id).attr('open')) {
            $("#" + slide_id).stop();
            $("#" + slide_id).slideUp(500);
            $("#" + slide_id).attr("open", false);
            $("#" + bind_id).children('i').css({
                'transform': 'rotate(180deg)'
            });
        } else {
            $("#" + slide_id).stop();
            $("#" + slide_id).slideDown(500);
            $("#" + slide_id).attr("open", true);
            $("#" + bind_id).children('i').css({
                'transform': 'rotate(360deg)'
            });
            callback();
        }
        setTimeout(function () {
            $(window).resize();
        }, 1000);
    });
}

//图片取证
var picNo;

//flag 参数用途：用于当日出入城的图片取证；原因：原固定的宽高超出了当日出入城详情页面设计弹出层的宽高，故另行写方法中的area
function getWithPicture(picture, flag) {
    var url = window.location.href,
        username, picname, wjmc;
    username = getUrlParam("user");
    picname = '1.jpg';
    layui.use('layer', function () {
        var layer = layui.layer;
        picNo = layer.open({
            type: 2,
            shade: 0.8,
            scrollbar: false,
            title: ['图片取证', 'font-size:22px;font-blod;font-weight: bold;padding-left:40px;color:white;background:#2180d4;'],
            content: 'http://15.225.1.36:8080/case/qz.html?dlm=' + username + '&url=' + encodeURIComponent(picture) + '&wjlx=1&wjmc=' + wjmc,
            area: (flag && flag == 1) ? ['100%', '100%'] : ['1300px', '700px'],
            success: function (layno, index) {
                $("#layui-layer" + index).css({
                    'z-index': 9999999999
                })
                $("#layui-layer-iframe1").css("height", 657);
                if ((flag && flag == 1)) {
                    $("#layui-layer1").css("top", 0);
                }
            }
        });
    })
}

$(function () {
    window.addEventListener('message', function (msg) {
        if (msg.origin == 'http://15.225.1.36:8080') {
            layui.use('layer', function () {
                layer.close(picNo);
            })
        }

    });
});

//快速布控
var fastReact = {
    _index: '',
    radioValue: '',
    reactChoose: function (reacttype, paramObj) {
        layui.use('layer', function () {
            var layer = layui.layer,
                _html = [];
            _html.push('<div style="margin-top:10px;">');
            _html.push('<form class="layui-form" onsubmit="return false">');
            _html.push('<label class="layui-form-label">布控类型：</label>');
            if (reacttype == 'pe') {
                _html.push('<input type="radio" lay-filter="react" name="react" value="1" title="人脸布控" checked>');
                _html.push('<input type="radio" lay-filter="react" name="react" value="2" title="车辆布控">');
            } else {
                _html.push('<input type="radio" lay-filter="react" name="react" value="1" title="人脸布控">');
                _html.push('<input type="radio" lay-filter="react" name="react" value="2" title="车辆布控" checked>');
            }
            _html.push('</form>');
            _html.push('<button id="submit" class="layui-btn normal-button layui-btn-sm" style="margin-top:20px;margin-left:150px;background-color:#1890ff;">确认选择</button>');
            _html.push('</div>');
            fastReact._index = layer.open({
                type: 1,
                title: '快速布控',
                content: _html.join(""),
                area: ['350px', '150px'],
                shadeClose: true,
                success: function (layno, index) {
                    //解决落脚点详情页面第一次加载 快速不空 的样式问题 因只有第一次是layui-layer-content 的高度计算是0，
                    $(".layui-layer-content").css("height", 107);
                    $(".layui-layer-content").css("overflow", "hidden");
                    $(".layui-layer-content >div").css("margin-top", 0);
                    layui.use(['layer', 'form'], function () {
                        var layer = layui.layer,
                            $ = layui.jquery,
                            form = layui.form; //必须先声明     
                        form.on('radio(react)', function (data) {
                            fastReact.radioValue = data.value;
                        });
                        form.render('radio'); //强制渲染 防止第一次渲染之后接下来的渲染失败
                    });
                    if (reacttype == 'pe') {
                        fastReact.radioValue = 1;
                    } else {
                        fastReact.radioValue = 2;
                    }
                    $("#submit").click(function () {
                        var message = {
                            src: serUrl_port_t1 + 'dispatched/disManagement',
                            name: '布控任务管理',
                        }
                        if (fastReact.radioValue == '1') {
                            message.params = {
                                token: paramObj.token,
                                imageAddress: encodeURIComponent(paramObj.imageAddress1),
                                clickType: 'createFace',
                                name: paramObj.name || '',
                                sex: paramObj.sex || '',
                                idcard: paramObj.idcard || '',
                                birthday: paramObj.birthday || '',
                                createCarVisible: true
                            }
                        } else {
                            message.params = {
                                token: paramObj.token,
                                imageAddress: encodeURIComponent(paramObj.imageAddress2),
                                platNo: paramObj.platNo || '',
                                platColor: paramObj.platColor || '',
                                clickType: 'createCar',
                                createCarVisible: true
                            }
                        }
                        window.parent.postMessage(message, '*');
                        layer.close(fastReact._index);
                    });
                }
            });

        });
    }
}

//一车一档
function oneCaroneDetail(param) {
    var message = {
        src: 'http://15.0.17.79:9000/#/echartable',
        name: '一车一档',
        params: {
            plateNum: param.plateNum,
            plateType: param.plateType,
            token: 'cXB8MjAxOC0wNS0yMiAwODowMDowMHwyMDE5LTA1LTIyIDEyOjAwOjAw'
        }
    }
    window.parent.postMessage(message, '*');
}

//地图选点
var mapChoose = {
    callback: null,
    init: function (fn) {
        // map.onDrawMapTips('rectangle', callBack);
        /**
         * 矩形|圆|多边形
         * rectangle/circle/polygon*/
        mapChoose.callback = fn;
        map.areaDraw("rectangle", mapChoose.getMapData);
    },
    getMapData: function (data) {
        if (!data) return;
        data = JSON.parse(data);
        if (!data.data.Devices || data.data.Devices.length == 0) return;
        var sbbhArr = [];
        $.each(data.data.Devices, function (i, item) {
            sbbhArr.push(item.DeviceId);
        });
        mapChoose.callback(sbbhArr);
    }

}

//地图车辆轨迹
var mapTraceObj = {
    _data: null,
    traceShowWithMap: function (data, callback) {
        mapTraceObj._data = null;
        layui.use('layer', function () {
            var layer = layui.layer;
            layer.open({
                type: 2,
                shadeClose: true,
                shade: 0.8,
                scrollbar: false,
                title: ['车辆轨迹', 'font-size:22px;font-blod;font-weight: bold;padding-left:40px;color:white;background:#2180d4;'],
                content: 'http://11.16.127.79/mapContainer/index.html?ip=' + location.href,
                area: ['1200px', '800px'],
                success: function (layero, index) {
                    // 获取子页面的iframe
                    var winds = $(layero).find("iframe")[0].contentWindow;
                    // 向子页面的全局函数child传参
                    // winds.child = "hello,layUI_children";
                    winds.child(data);
                },

                end: function () {
                    callback(mapTraceObj._data);
                }
            });
        })


    },
    _databack: function (data) {
        mapTraceObj._data = data;
    }
}

var chooseObj = {
    callback: null,
    data: [], //调接口获取的截取的图片
    layerindex: null,
    chooseObj: {},
    getData: function (obj, callback) {
        var _index;
        layui.use('layer', function () {
            _index = layer.load(1);
        });
        chooseObj.callback = callback;
        $.ajax({
            url: newfaceip + 'pictureCase/upPicture',
            type: 'post',
            datatype: 'json',
            contentType: 'application/json',
            data: JSON.stringify(obj.data),
            success: function (data) {
                layer.close(_index);
                chooseObj.data.length = 0;
                if (data.responseCode == 1000) {
                    if (data.content != null && data.content.length != 0) {
                        chooseObj.data.length = 0;
                        chooseObj.data = data.content;
                    } else {
                        layer.msg('无裁剪图片');
                        return false;
                    }
                    layui.use('layer', function () {
                        var layer = layui.layer;
                        chooseObj.layerindex = layer.open({
                            type: 2,
                            title: [obj.title, 'font-size:22px;font-blod;font-weight: bold;padding-left:40px;color:white;background:#2180d4;'],
                            content: '../person/personChoose.html',
                            area: ['800px', '700px']
                        });
                    });
                } else {
                    callback(data.message);
                }
            },
            error: function (err) {
                layer.close(_index);
                callback(9999);
            }
        })

    }
}

//获取当前时间的时分秒 返回的时间格式为'00:00:00'
function getCurrentDayTime() {
    var today = new Date();
    return today.pattern("HH:mm:ss");
}

//获取url中的参数
function getParametes(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) {
        return decodeURI(r[2]);
    }
    return null; //返回参数值
}

//数组对象根据某个值降序
var compare = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return 1;
        } else if (val1 > val2) {
            return -1;
        } else {
            return 0;
        }
    }
}

// function getId(ssId) {
//     var str;
//     var arr = ssId.split(",");
//     arr.splice(30, 31);
//     return str = arr.join(",");
// }


function getVehicleBrandName(tempData, i) {
    var ssId = "";
    if (i < tempData.length) {
        ssId = tempData[i]['VEHICLE_BRAND'];
        $.ajax({
            type: 'get',
            url: serUrl_port1 + "VIAS/System/Dictionary/FindDatailBySSID/" + ssId,
            dataType: 'json',
            async: false,
            success: function (result) {
                if (result != undefined) {
                    tempData[i]['NAME'] = result.NAME;
                }
                getVehicleBrandName(tempData, ++i);
            },
            error: function () {
                getVehicleBrandName(tempData, ++i);
            }
        });
    }
}

function getApeName(tempData, i) {
    var apeId = "";
    if (i < tempData.length) {
        apeId = tempData[i]['DEVICE_ID'];
        $.ajax({
            type: 'get',
            url: serUrl_port6 + "VIAS/System/Ape/findByApeId/" + apeId,
            dataType: 'json',
            async: false,
            success: function (result) {
                if (result != undefined) {
                    tempData[i]['SS_APE_NAME'] = result.SBMC;
                }
                getApeName(tempData, ++i);
            },
            error: function () {
                getApeName(tempData, ++i);
            }
        });
    }
}

//获取当前时间并格式化
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


function drawLine(data) {
    var image = new Image();
    $(".kLine").css({ "width": 0, "height": 0, "top": 0, "left": 0 });
    //原图片原始地址（用于获取原图片的真实宽高，当<img>标签指定了宽、高时不受影响）
    if ($("#carScenePic").attr("isLoad") == "true") {
        var w = $("#carScenePic").width();
        var h = $("#carScenePic").height();
        image.src = $("#carScenePic").attr("src");
        var rectWidth = w / image.width * (data.rightBottomX - data.leftTopX);
        var rectHeight = h / image.height * (data.rightBottomY - data.leftTopY);
        var rectLeft = w / image.width * data.leftTopX + $("#carScenePic").offset().left;
        var rectTop = h / image.height * data.leftTopY + $("#carScenePic").offset().top;
        $(".kLine").css({ "width": rectWidth, "height": rectHeight, "top": rectTop, "left": rectLeft });
        $("#carScenePic").attr("isLoad", true);
    } else {
        $("#carScenePic").on("load", function () {
            var w = $(this).width();
            var h = $(this).height();
            image.src = $(this).attr("src");
            var rectWidth = w / image.width * (data.rightBottomX - data.leftTopX);
            var rectHeight = h / image.height * (data.rightBottomY - data.leftTopY);
            var rectLeft = w / image.width * data.leftTopX + $("#carScenePic").offset().left;
            var rectTop = h / image.height * data.leftTopY + $("#carScenePic").offset().top;
            $(".kLine").css({ "width": rectWidth, "height": rectHeight, "top": rectTop, "left": rectLeft });
            $("#carScenePic").attr("isLoad", true);
        });
    }
}

function getWkk(deviceId) {
    var backData = false;
    $.ajax({
        type: 'get',
        url: '/vias_app/static/common/js/jghkk.json',
        dataType: 'json',
        async: false,
        success: function (data) {
            var filterData = data.deviceInfo.filter(item => item.devId == deviceId);
            if (filterData.length > 0) {
                backData = true;
            } else {
                backData = false;
            }
        }
    });
    return backData;
}

/**
 * 车身颜色翻译
 * @param vehicleColor
 * @param platecolorEle
 */
function vehicleColorTranslation(vehicleColor, ele) {
    var result = "未知";
    if (vehicleColor == '1') {
        result = '黑';
    }
    if (vehicleColor == '0') {
        result = '未知';
    }
    if (vehicleColor == '18') {
        result = '深灰';
    }
    if (vehicleColor == '99') {
        result = '其他';
    }
    if (vehicleColor == '4') {
        result = '红';
    }
    if (vehicleColor == '6') {
        result = '黄';
    }
    if (vehicleColor == '11') {
        result = '青';
    }
    if (vehicleColor == '5') {
        result = '蓝';
    }
    if (vehicleColor == '10') {
        result = '紫';
    }
    if (vehicleColor == '12') {
        result = '粉';
    }
    if (vehicleColor == '8') {
        result = '棕';
    }
    if (vehicleColor == '2') {
        result = '白';
    }
    if (vehicleColor == '3') {
        result = '灰';
    }
    if (vehicleColor == '7') {
        result = '橙';
    }
    if (vehicleColor == '14') {
        result = '银';
    }
    if (vehicleColor == '15') {
        result = '褐';
    }
    if (vehicleColor == '16') {
        result = '银白';
    }
    if (vehicleColor == '17') {
        result = '深蓝';
    }
    if (vehicleColor == '13') {
        result = '金色';
    }
    $("#" + ele).text(result);
}
// 获取视频登陆接口进行Login
var videoplay=0;//重复请求次数
function videoDisplayFucZD(deviceId, videoid) {
    var videoElement = document.getElementById(videoid);
    videoElement.setAttribute("src","http://11.15.235.161:10005/play.html?serial=11010800002000000003&code="+deviceId+"&aspect=fullscreen");
}
// 获取视频登陆接口进行Login
function videoDisplayFucZD1(deviceId, videoid) {
    var videoElement = document.getElementById(videoid);
    videoElement.setAttribute("src","http://11.15.238.107:10000/play.html?serial=10101400002000000179&code="+deviceId+"&aspect=fullscreen");
}
function videoDisplayFucStop(deviceId) {
    $.ajax({
        type: 'GET',
        dataType: "JSON",
        contentType: "application/json",
        data:{
            serial:"11010800002000000003",
            code:deviceId,
            check_outputs:"true"
        },
        url: "http://11.15.235.161:10005/api/v1/stream/stop",
        success: function (data) {
            if (data == "OK") {
                console.log("关闭成功")
         }
    }
    })
}
// 获取视频登陆接口进行Login
function videoDisplayFuc(deviceId, fun) {
    parent.window.sessionStorage.setItem("deviceVideoId", deviceId);
    var videoDisplayLoginID = parent.window.sessionStorage.getItem("videoDisplayLoginID");
    var wkkvideoDisplayLoginID = parent.window.sessionStorage.getItem("wkkvideoDisplayLoginID");
    // 视频登录
    var splogin_url = "http://11.16.127.79:8013/Video/login";
    var splogin_url_wkk = "http://11.16.127.79:8013/Video/loginwkk";
    var tempFlag = getWkk(deviceId);
    if (!tempFlag) {
        if (videoDisplayLoginID) {
            fun(videoDisplayLoginID);
        } else {
            //获取球机loginId
            $.ajax({
                type: 'POST',
                dataType: "JSON",
                contentType: "application/json",
                data: JSON.stringify({ "ServerIP": "11.15.235.156", "User": "SUPPER_NONEED_USER", "Pwd": " ", "bayonet": " " }),
                // async: false,
                url: splogin_url,
                success: function (data) {
                    if (data.RetCode == 200) {
                        // 获取ip和port
                        parent.window.sessionStorage.setItem("videoDisplayLoginID", data.LoginID);
                        fun(data.LoginID);
                    } else {
                        alert("获取失败")
                    }
                }
            })
        }
    } else {
        if (wkkvideoDisplayLoginID) {
            fun(wkkvideoDisplayLoginID);
        } else {
            //获取球机loginId
            $.ajax({
                type: 'POST',
                dataType: "JSON",
                contentType: "application/json",
                data: JSON.stringify({ "ServerIP": "11.15.232.70", "User": "SUPPER_NONEED_USER", "Pwd": " ", "bayonet": " " }),
                // async: false,
                url: splogin_url_wkk,
                success: function (data) {
                    if (data.RetCode == 200) {
                        // 获取ip和port
                        parent.window.sessionStorage.setItem("wkkvideoDisplayLoginID", data.LoginID);
                        fun(data.LoginID);
                    } else {
                        alert("获取失败")
                    }
                }
            })
        }
    }
}
// 视频退出接口进行Logout
function videoStopFuc() {
    // 视频退出
    var splogout_url = "http://11.16.127.79:8013/Video/logout";
    var splogout_url_wkk = "http://11.16.127.79:8013/Video/logoutwkk";
    if (window.sessionStorage.getItem("videoSession")) {
        if (getWkk(window.sessionStorage.getItem("deviceVideoId"))) {
            $.ajax({
                type: 'POST',
                dataType: "JSON",
                contentType: "application/json",
                async: false,
                data: JSON.stringify({ "LoginID": window.sessionStorage.getItem("wkkvideoDisplayLoginID"), "Session": window.sessionStorage.getItem("videoSession") }),
                url: "http://11.16.127.79:8013/Video/stoprealwkk",
                success: function (data) {
                    console.log(data)
                    sessionStorage.removeItem("videoSession");
                }
            });
        } else {
            $.ajax({
                type: 'POST',
                dataType: "JSON",
                contentType: "application/json",
                async: false,
                data: JSON.stringify({ "LoginID": window.sessionStorage.getItem("videoDisplayLoginID"), "Session": window.sessionStorage.getItem("videoSession") }),
                url: "http://11.16.127.79:8013/Video/stopreal",
                success: function (data) {
                    console.log(data)
                    sessionStorage.removeItem("videoSession");
                }
            });
        }
    }
    if (window.sessionStorage.getItem("videoDisplayLoginID")) {
        $.ajax({
            url: splogout_url,
            type: 'POST',
            async: false,
            contentType: "application/json", //必须有
            dataType: "json", //表示返回值类型，不必须
            data: JSON.stringify({ "LoginID": window.sessionStorage.getItem("videoDisplayLoginID") }),
            success: function (data) {
                sessionStorage.removeItem("deviceVideoId");
                sessionStorage.removeItem("videoDisplayLoginID");

                console.log(data)
            }
        });
    }
    if (window.sessionStorage.getItem("wkkvideoDisplayLoginID")) {

        $.ajax({
            url: splogout_url_wkk,
            type: 'POST',
            async: false,
            contentType: "application/json", //必须有
            dataType: "json", //表示返回值类型，不必须
            data: JSON.stringify({ "LoginID": window.sessionStorage.getItem("wkkvideoDisplayLoginID") }),
            success: function (data) {
                sessionStorage.removeItem("deviceVideoId");
                sessionStorage.removeItem("wkkvideoDisplayLoginID");
                console.log(data)
            }
        });
    }
}
function getGJinof(start,end,fun){
    $.ajax({
        type: 'get',
        dataType: "json",
        data: {
            httpurl: "/cloudsearch?output=json&index=direction&action=route&origin="+start.lat+","+start.lng+"&destination="+end.lat+","+end.lng+"&waypoints=&mode=CAR&tactics=1"
        },
        url: "http://11.16.127.79:5013/VIAS/web/snapshot/baidu/BayonetMarking",
        success: function (data) {
            fun(data);
        }
        })
}
function getNextDate(date, day) {
    var dd = new Date(date);
    dd.setDate(dd.getDate() - day);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
    var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
    return y + "-" + m + "-" + d;
};
function getDatetime() {
    var d = new Date();
    var year = d.getFullYear();
    var month = change(d.getMonth() + 1);
    var day = change(d.getDate());
    var hour = change(d.getHours());
    var minute = change(d.getMinutes());
    var second = change(d.getSeconds());

    function change(t) {
        if (t < 10) {
            return "0" + t;
        } else {
            return t;
        }
    }

    var time = year + '-' + month + '-' + day;

    return time;
}






































